import { Radio, Select, message } from 'antd';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import { selectQuarter, selectQuarterNoOkr, selectOkrByCondition } from '@/services/okr'

const TimeHeader = (props, ref) => {
  const {
    editYear,
    editQuarter,
    isDetailFlag,
    isPreview,
    updateList = () => {},
    updateNewList = () => {},
    pageSource = '',
    departmentId = '',
    okrType,
  } = props;
  const [year, setYear] = useState();
  const [okrYearList, setOkrYearList] = useState([]);
  const [quarter, setQuarter] = useState();
  const [quarterList, setQuarterList] = useState([]);
  useEffect(() => {
    const currYear = new Date().getFullYear();
    let yearLists = new Array(10).fill(0).map((item, index) => {
      return index === 0 ? currYear : Number(currYear) + Number(index);
    });
    setOkrYearList(yearLists);
    if (!pageSource) {
      // 筛选出对应的周期
      const cacheYear = localStorage.getItem('year');
      setYear(cacheYear ? cacheYear : currYear);
      getQuarterFun(
        cacheYear
          ? isNaN(Number(cacheYear))
            ? currYear
            : Number(cacheYear)
          : currYear,
      );
    } else if(!isDetailFlag && pageSource){ // 新增 需查询最近可创建的周期
        initAddOkrTime()
    }
  }, []);

  useEffect(() => {
    if (pageSource) {
      // 详情页
      if (isDetailFlag) {
        setYear(editYear);
        setQuarter(editQuarter);
      }
    }
  }, [editYear, editQuarter]);
  useImperativeHandle(ref, () => ({
    year,
    quarter,
    getQuarterFun: (year, mode, id) => { getQuarterFun(year, mode, id)}
  }));

  const initAddOkrTime = async () => {
    const res = await selectQuarterNoOkr({ type: okrType, departmentId: departmentId || '' });
    if(res.code == 200) {
        const list = res.data?.quartList || []
        setYear(res.data.year)
        setQuarter(list[0].quarter + '')
    }
  }

  const judgeIsExistOkr = async (params, value, callback) => {
    const res = await selectOkrByCondition(params);
    if(res.data.num == '1') { // 已存在，不更新周期
        message.error('当前周期已存在OKR，不可以创建，请选择其他周期')
    } else {
        callback(value)
    }
  };
  const handleChangeOkrYear = (value) => {
    localStorage.removeItem('year');
    localStorage.removeItem('quarter');
    if (pageSource === 'okr-detail') {
      judgeIsExistOkr(
        {
          year: value,
          quarter,
          type: okrType,
          departmentId: departmentId || '',
        },
        value,
        setYear,
      );
    } else {
      getQuarterFun(value);
    }
  };
  const getQuarterFun = (value, mode = '0', currId = '') => {
    selectQuarter({year: value, type: mode == '0' ? '2' : '1', id: currId}).then((res) => {
      if(res.code == 200){
        const list = res.data.quartList.map(item => item.quarter);
        if(list.length > 0) {
          setQuarterList(list);
          setYear(value)
          setQuarter(list[0])
          updateList(value, list[0], mode == '0' ? '2' : '1', currId, '1')
        } else {
          setQuarterList([]);
          setYear(value)
          setQuarter('')
          updateNewList()
        }
      }
    })
  };
  const handleChangeOkrCycle = (value) => {
    if (pageSource === 'okr-detail') {
      judgeIsExistOkr(
        {
          year,
          quarter: value,
          type: okrType,
          departmentId: departmentId || '',
        },
        value,
        setQuarter,
      );
    } else {
      // setQuarter(value);
      updateList(year, value, '', '', '2');
    }
  };
  const handleChangeOkrCycle2 = (e) => {
      setQuarter(e.target.value);
      updateList(year, e.target.value, '', '', '2');
  };

  const getQ = (time) => {
    let q = '年度';
    switch (time) {
      case '0':
        q = '年度';
        break;
      case '1':
        q = 'Q1';
        break;
      case '2':
        q = 'Q2';
        break;
      case '3':
        q = 'Q3';
        break;
      case '4':
        q = 'Q4';
        break;
      default:
        q = '年度';
        break;
    }
    return q;
  };
  return (
    <>
      <Select
        disabled={pageSource === 'okr-detail' ? isDetailFlag : false}
        value={year}
        style={{ width: 120, marginRight: 10 }}
        onChange={handleChangeOkrYear}
      >
        {okrYearList.map((item, index) => (
          <Option key={`${index}`} value={item}>
            {item}年
          </Option>
        ))}
      </Select>
      {pageSource === 'okr-detail' ? (
        <Select
          disabled={isDetailFlag || isPreview}
          value={quarter}
          style={{ width: 120 }}
          onChange={handleChangeOkrCycle}
        >
          <Option value="0">年度</Option>
          <Option value="1">Q1</Option>
          <Option value="2">Q2</Option>
          <Option value="3">Q3</Option>
          <Option value="4">Q4</Option>
        </Select>
      ) : (
        <Radio.Group onChange={handleChangeOkrCycle2} value={quarter}>
          {quarterList.map((item, index) => (
            <Radio key={`${index}`} value={item}>
              {getQ(item)}
            </Radio>
          ))}
        </Radio.Group>
      )}
    </>
  );
};
export default forwardRef(TimeHeader);
